package com.bookstore.servlet.admin;

import com.bookstore.entity.User;
import com.bookstore.service.UserService;
import com.bookstore.service.impl.UserServiceImpl;
import com.bookstore.servlet.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/admin/user.do")
public class UserServlet extends BaseServlet {
    UserService userService = new UserServiceImpl();

    protected void queryAll(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        List<User> users = userService.queryAll();
        request.setAttribute("users", users);
        request.getRequestDispatcher("/admin/user_list.jsp").forward(request, response);
    }

    protected void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //根据登录方法 查询到对应的用户信息
        User user = userService.login(new User(username, password));
        if (user != null) {
            //1.登录成功的用户信息 保存到 Session 域中
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            //2.跳转首页
            response.sendRedirect("./index.jsp");
        } else {
            response.sendRedirect("./login.html");
        }
    }

    protected void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //注销方法
        //1.销毁 Session
        request.getSession().invalidate();
        //2.重定向回首页
        response.sendRedirect("./login.html");
    }

}
